package com.gaimall.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.gaimall.beans.pagebean.DetailPage;
import com.gaimall.beans.pagebean.RecomPage;
import com.gaimall.beans.pagebean.ResultPage;
import com.gaimall.beans.xmlbean.Result;
import com.gaimall.beans.xmlbean.Result_idsearch;
import com.gaimall.beans.xmlbean.Result_recom;
import com.gaimall.services.ApiService;

@Controller
public class BaseController {
	@Autowired
	ApiService apiservice;

	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);

	/**
	 * 返回搜索结果页面
	 * 
	 * @param kw
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/search")
	public String search(@RequestParam String kw, @RequestParam String page,
			@RequestParam String sorter, Model model, HttpServletRequest request) {
		logger.info("nothing!");

		String r_type = request.getParameter("type");
		String r_source = request.getParameter("source");
		String r_brand = request.getParameter("brand");

		model.addAttribute("kw", kw);
		model.addAttribute("pageno", page);
		Result rs = apiservice.getResult(kw, page, sorter, r_type, r_brand, r_source);
		ResultPage rp = new ResultPage(rs, kw, page, sorter, r_type, r_brand, r_source);

		model.addAttribute("rp", rp);

		// 加入分页
		String mapping = request.getServletPath();
		model.addAttribute("pagelink", apiservice.getPagelink(Integer.parseInt(page),
				(Integer.parseInt(rs.getLength()) - 1) / 36 + 1, kw, mapping, r_type, r_source,
				r_brand, sorter));

		return "result";
	}

	/**
	 * 返回商品详细页面
	 * 
	 * @param kw
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/item")
	public String detail(@RequestParam String id, @RequestParam String page, Model model,
			HttpServletRequest request) {
		logger.info("nothing!");

		Result_idsearch rs = apiservice.getResult_IdSearch(id, page);
		Result_recom rr = apiservice.getResult_recom(id);
		DetailPage dp = new DetailPage(rs, id, page);
		RecomPage rp = new RecomPage(rr);

		model.addAttribute("dp", dp);
		model.addAttribute("rp", rp);
		return "detail";
	}

}
